from commonTool.logs.logs_wrapper import LogUtil
from manager import api
from manager.config import Base_File_Config as fileConfig
from manager.config.Base_File_Config import BASE_PATH
from EventMessageWeb.enums.ApiRespCodeEnums import api_response_code as ApiCodeEnums
from manager.exception.domain.ApiResponse import api_response
from manager.tool import Read_Properties as read

resp_info = api_response()
'''
*******************************************************************************
                测试工具类
*******************************************************************************
'''

logs = LogUtil()


def buildEnvironmentVariable():
    """
    配置测试运行环境变量文件操作对象
    :return: 操作 properties 对象
    """
    file_path = fileConfig.ENVIRONMENT_PROPERTIES_PATH
    return read.Properties(file_path, 'utf-8')  # 操作 properties 对象


def assertResponse(responseCode: int, myCode: int):
    """
    断言响应返回值是否符合预期
    :param responseCode:  返回响应码
    :param myCode:        预期响应码
    :return:            None
    """
    resp = {
        "responseCode": responseCode,
        "responseMsg": ApiCodeEnums.search_msg_by_code(responseCode),
        "myCode": myCode,
        "myMsg": ApiCodeEnums.search_msg_by_code(myCode)
    }
    # 断言 响应码
    if responseCode != myCode:
        resp_info.new_fail(code=ApiCodeEnums.getCode(ApiCodeEnums.INTERFACE_ASSERTION_FAIL),
                           msg=ApiCodeEnums.getMsg(ApiCodeEnums.INTERFACE_ASSERTION_FAIL),
                           data=resp)
    else:
        resp_info.new_success()


def writeVarProperties(key, value):
    """
    写入环境变量
    :param key:     变量key  支持传入多值，数组格式
    :param value:   变量值   支持传入多值，数组格式，下标和Key一一对应
    :return:        Void
    """
    p = buildEnvironmentVariable()
    if type(key) is str:
        p.set(key, str(value))
    else:
        for i in range(0, len(key)):
            p.set(key[i], str(value[i]))
            validReturnPropertiesKey(key[i])
            print('成功写入环境变量  -->  ', key[i])
        return
    validReturnPropertiesKey(key)
    print('成功写入环境变量  -->  ', key)


def validReturnPropertiesKey(key):
    """
    校验环境变量 Key 是否存在 并返回 key 对应的 value
    :param key:    变量key
    :return:       环境变量key的值
    """
    # 构建操作环境变量对象
    p = buildEnvironmentVariable()
    if p.get(key) is None or len(p.get(key)) == 0 or p.get(key) == '':
        raise KeyError('定义Key ，未赋值  -->  ', key)
    return p.get(key)


@logs
def printAndLogResponse(r):
    """
    打印输出和保存日志
    :param r:  response对象
    :return:    Void
    """
    # 打印输出结果
    url = str(r.request.url)
    logs.info(f' url  --> {url}')
    logs.info(f'响应头 --> {r.headers}')
    logs.info(f'响应体 --> {r.json()}')


def getCommonTokenWriteRequestHead():
    """
    获取公共token 写入请求头
    :return:    Void
    """
    # 构建操作环境变量对象
    p = buildEnvironmentVariable()
    token = p.get('token')
    api.headers['Auth-Token'] = token


if __name__ == '__main__':
    # assertResponse(0, 100000)
    logs.error(BASE_PATH)
